/**
 * 
 */
package com.cnc.fd.util;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import com.cnc.bas.util.Log;

/**
 * @author 阿闲
 *
 */
public class ShellUtil {
	
	private static final Log log = Log.getLogger(ShellUtil.class);
	
	public static int runShell(String command){
		
		Process p = null;

		InputStreamReader is = null;		
		LineNumberReader input = null;
		
		InputStreamReader es = null;
		LineNumberReader error = null;
		
		try {
				log.logDebug("execute command: " + command);
			
				p = Runtime.getRuntime().exec(command);
				is = new InputStreamReader(p.getInputStream());	
				input = new LineNumberReader(is);
				es = new InputStreamReader(p.getErrorStream());
				error = new LineNumberReader(es);
				String line;
				
				while (( line = input.readLine()) != null) {					
					log.logInfo(line);						
				}
				
				while ((line = error.readLine()) != null){					
					log.logInfo(line);						
				}
				
				p.waitFor();
				
				return p.exitValue();
				
			} catch (Exception e) {
				log.logError("run shell error", e);	
				return -1;	
				
			} finally {
				try{
					
					if(input != null)
						input.close();
				
					if(is != null)
						is.close();
				
					if(p != null)
						p.destroy();
					
				}catch(Exception e){
					//do nothing
				}
				
			}	
		
	}
}
